package com.eqdd.yiqidian.ui.discover.makerspace

import android.content.Intent
import android.graphics.Color
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import com.eqdd.yiqidian.R
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector
import com.eqdd.yiqidian.base.BaseActivity
import com.eqdd.yiqidian.base.Config
import com.eqdd.yiqidian.bean.MakerMessageBean
import com.eqdd.yiqidian.bean.MakerVisitorBean
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource
import com.eqdd.yiqidian.http.DialogCallBack
import com.eqdd.yiqidian.http.HttpConfig
import com.eqdd.yiqidian.http.HttpResult
import com.eqdd.yiqidian.http.JsonConverter
import com.eqdd.yiqidian.kotlin.BaseRecyclerViewAdapter
import com.eqdd.yiqidian.kotlin.deleteDialog
import com.eqdd.yiqidian.kotlin.toArrayList
import com.eqdd.yiqidian.ui.InputDialogActivity
import com.eqdd.yiqidian.ui.mine.UserCardActivity
import com.eqdd.yiqidian.ui.yiqiyue.AddArticleActivity
import com.eqdd.yiqidian.utils.TimeUtil
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import com.lzy.okrx2.adapter.FlowableBody
import com.shizhefei.mvc.MVCCoolHelper
import io.reactivex.Flowable
import kotlinx.android.synthetic.main.activity_maker_space.*
import kotlinx.android.synthetic.main.list_item_150.view.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.io.Serializable
import java.util.*

/**
 * Created by jhj on 18-8-3.
 */
class MakerSpaceActivity : BaseActivity() {


    companion object {
        const val DIARY = "diary"
        const val PRODUCT = "product"
        const val PERSONAL_FILE = "personal_file"
        const val COLLECT = "collect"

        const val diary = "写日志,我的日志"
        const val product = "课程"
        const val file = "所属行业,个人信息,个人优势,个人相册"
        const val collect = "收藏的企业,收藏的产品,收藏的创客,收藏的课程"
        const val leftStr = """
                            [
                                {"id":"1","label":"日志"},
                                {"id":"2","label":"产品信息"},
                                {"id":"3","label":"个人档案"},
                                {"id":"4","label":"留言"},
                                {"id":"5","label":"访客"},
                                {"id":"7","label":"我的收藏"}
                            ]
                            """
    }


    private lateinit var adapter: MakerSpaceAdapter

    private var makerGuid: String? = null
    private var dataList: List<LeftItemBean>? = null
    private var clickMessageBean: MakerMessageBean? = null

    private var isFirst2Message: Boolean = true
    private var isFirst2Visitor = true

    private var messageMvcHelper: MVCCoolHelper<List<MakerMessageBean>>? = null
    private var visitorMvcHelper: MVCCoolHelper<List<MakerVisitorBean>>? = null

    override fun initBinding() {
        setContentView(R.layout.activity_maker_space)
        initTopTitleBar(View.VISIBLE, "创客空间")
        makerGuid = user.guid
    }


    override fun initData() {
        dataList = Gson().fromJson(leftStr, object : TypeToken<List<LeftItemBean>>() {}.type)
        recycler_left.layoutManager = LinearLayoutManager(this)
        adapter = MakerSpaceAdapter(this)
        adapter.dataList = dataList as ArrayList<LeftItemBean>
        recycler_left.adapter = adapter

        //右侧菜单栏
        recycler_right.addItemDecoration(DividerLineItemDecoration(this))
        recycler_right.layoutManager = LinearLayoutManager(this)
        recycler_right.visibility = View.VISIBLE

        dataList?.get(0)?.isChecked = true
        refreshList(diary, DIARY)
    }


    override fun setView() {

    }

    private fun resetView(pos: Int) {
        recycler_right.visibility = View.GONE
        recycler_right.removeAllViews()
        coolRefresh_message.visibility = View.GONE
        coolRefresh_visitor.visibility = View.GONE
        relativeLayout.visibility = View.GONE
        messageMvcHelper?.loadView?.restore()
        visitorMvcHelper?.loadView?.restore()


        when (pos) {
            1, 2, 3, 7 -> recycler_right.visibility = View.VISIBLE
            4 -> coolRefresh_message.visibility = View.VISIBLE
            5 -> coolRefresh_visitor.visibility = View.VISIBLE
        }
    }

    private fun refreshRight(bean: LeftItemBean) {
        when (bean.id) {
            1 -> {
                resetView(1)
                refreshList(diary, DIARY)
            }
            2 -> {
                resetView(2)
                refreshList(product, PRODUCT)
            }
            3 -> {
                resetView(3)
                refreshList(file, PERSONAL_FILE)
            }
            4 -> {
                resetView(4)
                if (isFirst2Message) {
                    message()
                } else {
                    messageMvcHelper?.refresh()
                }
            }
            5 -> {
                resetView(5)
                if (isFirst2Visitor) {
                    visitor()
                } else {
                    visitorMvcHelper?.refresh()
                }
            }
            7 -> {
                resetView(7)
                refreshList(collect, COLLECT)
            }
        }
    }


    private fun message() {
        isFirst2Message = false
        var pageNum = 0
        val list = arrayListOf<MakerMessageBean>()
        messageMvcHelper = MVCCoolHelper<List<MakerMessageBean>>(coolRefresh_message)
        recycler_message.layoutManager = LinearLayoutManager(this)
        recycler_message.addItemDecoration(DividerLineItemDecoration(this))
        val slimAdapterEx = SlimAdapterEx.create()
                .register<MakerMessageBean>(R.layout.list_item_156, SlimInjector<MakerMessageBean> { data, injector ->
                    injector?.text(R.id.tv_name, data?.staffName)
                            ?.text(R.id.tv_depart, String.format(Locale.CHINA, "%s - %s", data?.departName, data?.postName))
                            ?.text(R.id.tv_time, TimeUtil.formatWebTime(data?.createTime))
                            ?.imageCircle(R.id.iv_photo, data?.iphoto)
                            ?.text(R.id.tv_message, data?.message)
                            ?.clicked(R.id.iv_photo) {
                                startActivity<UserCardActivity>(Config.GUID to data?.creater)
                            }
                            ?.with<RecyclerView>(R.id.recyclerView) { recyclerView ->
                                var mSlimAdapterEx: SlimAdapterEx<MakerMessageBean>? = null
                                recyclerView.layoutManager = LinearLayoutManager(this)
                                data?.childList?.let {
                                    mSlimAdapterEx = SlimAdapterEx.create()
                                            .register<MakerMessageBean>(R.layout.list_item_162, SlimInjector<MakerMessageBean> { t1, t2 ->
                                                val span = SpannableString("创客回复：" + t1?.message)
                                                span.setSpan(ForegroundColorSpan(Color.GRAY), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
                                                t2
                                                        ?.gone(R.id.tv_label)
                                                        ?.text(R.id.tv_reply, span)
                                                        ?.longClicked(R.id.tv_reply) { view ->
                                                            deleteDialog(HttpConfig.BASE_URL + HttpConfig.MESSAGE_DELETE, "是否删除“${t1?.message}”？", "type" to 2, "msgId" to t1?.id, isFinish = false) {
                                                                val index = it.indexOf(t1)
                                                                mSlimAdapterEx?.data?.removeAt(index)
                                                                mSlimAdapterEx?.notifyItemRemoved(index)
                                                            }
                                                            true
                                                        }
                                            })
                                            .attachTo(recyclerView)
                                            .updateData(it.toArrayList() as List<MakerMessageBean>) as SlimAdapterEx<MakerMessageBean>?
                                }

                            }
                            ?.clicked(R.id.tv_message) {
                                clickMessageBean = data
                                startActivityForResult<InputDialogActivity>(Config.INPUT, Config.TALK_TO to clickMessageBean?.upname)
                            }
                })
                .attachTo(recycler_message)
                .updateData(list as List<MakerMessageBean>?) as SlimAdapterEx<MakerMessageBean>?
        val dataSource = ModelRx2DataSource<MakerMessageBean>(ModelRx2DataSource.OnLoadSource<MakerMessageBean> { page, register ->
            if (page == 1) {
                pageNum = 0
            }
            OkGo.post<HttpResult<List<MakerMessageBean>>>(HttpConfig.BASE_URL + HttpConfig.MESSAGE_GET)
                    .params("makerGuid", makerGuid)
                    .params("page", pageNum)
                    .converter(object : JsonConverter<HttpResult<List<MakerMessageBean>>>() {
                        override fun test() {
                            super.test()
                        }
                    })
                    .adapt(FlowableBody<HttpResult<List<MakerMessageBean>>>())
                    .flatMap({ result ->
                        if (page == 1) {
                            messageMvcHelper?.isAutoLoadMore = true
                        }
                        pageNum = result.page
                        Flowable.just<MutableList<MakerMessageBean>>(
                                if (result.items == null)
                                    ArrayList()
                                else
                                    result.items as MutableList<MakerMessageBean>?
                        )
                    })
        }, 10)
        messageMvcHelper?.setDataSource(dataSource)
        messageMvcHelper?.adapter = slimAdapterEx
        messageMvcHelper?.refresh()
    }

    private fun visitor() {
        var pageNum = 0
        val list = arrayListOf<MakerVisitorBean>()
        isFirst2Visitor = false
        visitorMvcHelper = MVCCoolHelper<List<MakerVisitorBean>>(coolRefresh_visitor)
        recycler_visitor.layoutManager = LinearLayoutManager(this)
        recycler_visitor.addItemDecoration(DividerLineItemDecoration(this))
        val slimAdapterEx = SlimAdapterEx.create()
                .register<MakerVisitorBean>(R.layout.list_item_155, SlimInjector<MakerVisitorBean> { data, injector ->
                    injector?.text(R.id.tv_name, data?.staffName)
                            ?.text(R.id.tv_depart, String.format(Locale.CHINA, "%s - %s", data?.departName, data?.postName))
                            ?.text(R.id.tv_time, TimeUtil.formatWebTime(data?.createTime))
                            ?.text(R.id.tv_preview, data?.useroption)
                            ?.imageCircle(R.id.iv_photo, HttpConfig.BASE_URL + data?.iphoto)
                            ?.clicked(R.id.iv_photo) {
                                startActivity<UserCardActivity>(Config.GUID to data?.creater)
                            }

                })
                .attachTo(recycler_visitor)
                .updateData(list as List<MakerVisitorBean>?) as SlimAdapterEx<MakerVisitorBean>?
        val dataSource = ModelRx2DataSource<MakerVisitorBean>(ModelRx2DataSource.OnLoadSource<MakerVisitorBean> { page, register ->
            if (page == 1) {
                pageNum = 0
            }
            OkGo.post<HttpResult<List<MakerVisitorBean>>>(HttpConfig.BASE_URL + HttpConfig.VISITOR_GET)
                    .params("makerGuid", makerGuid)
                    .params("page", pageNum)
                    .converter(object : JsonConverter<HttpResult<List<MakerVisitorBean>>>() {
                        override fun test() {
                            super.test()
                        }
                    }).adapt(FlowableBody<HttpResult<List<MakerVisitorBean>>>())
                    .flatMap({ result ->
                        if (page == 1) {
                            visitorMvcHelper?.isAutoLoadMore = true
                        }
                        pageNum = result.page
                        Flowable.just<MutableList<MakerVisitorBean>>(if (result.items == null) ArrayList() else result.items as MutableList<MakerVisitorBean>?)
                    })


        }, 10)

        visitorMvcHelper?.setDataSource(dataSource)
        visitorMvcHelper?.adapter = slimAdapterEx
        visitorMvcHelper?.refresh()
    }


    fun leftItemOnClick(bean: LeftItemBean) {
        refreshRight(bean)
        bean.isChecked = !bean.isChecked
        dataList?.forEach {
            if (it.label != bean.label) {
                it.isChecked = false
            }
        }
        adapter.notifyDataSetChanged()
    }


    private fun refreshList(str: String, type: String) {
        val adapter = ListAdapter(type)
        adapter.dataList = str.split(",").toList().toArrayList()
        recycler_right.adapter = adapter
    }

    private fun responseMessage(msg: String) {
        OkGo.post<HttpResult<MakerMessageBean>>(HttpConfig.BASE_URL + HttpConfig.MESSAGE_ADD)
                .params("userGuid", user.guid)
                .params("userCompanyId", user.companyId)
                .params("message", msg)
                .params("parentId", clickMessageBean?.id ?: 0)
                .params("parentUserGuid", clickMessageBean?.parentUserGuid)
                .params("firstCommentId", clickMessageBean?.id ?: 0)
                .params("makerGuid", makerGuid)
                .params("objectId", 0)
                .params("objectType", 0)

                .execute(object : DialogCallBack<HttpResult<MakerMessageBean>>(this) {
                    override fun onSuccess(response: Response<HttpResult<MakerMessageBean>>?) {
                        val result = response?.body()
                        if (result?.status == 200) {
                            messageMvcHelper?.refresh()
                        } else {
                            toast(result?.msg ?: "")
                        }
                    }

                })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Config.SUCCESS) {
            when (requestCode) {
                Config.INPUT -> {
                    val str = data?.getStringExtra(Config.CONTENT)
                    responseMessage(str ?: "")
                }
            }
        }
    }


    inner class ListAdapter(val type: String) : BaseRecyclerViewAdapter<String>() {

        override fun onCreateView(viewType: Int): Int {
            return R.layout.list_item_150
        }

        override fun onBindViewItemViewHolder(holder: ItemViewHolder, bean: String, position: Int) {
            holder.itemView.let {
                it.tv_content.text = bean
                it.onClick {
                    if (type == DIARY) {
                        when (position) {
                            0 -> startActivity<AddArticleActivity>()
                            1 -> startActivity<MakerDiaryListActivity>()
                        }
                    } else if (type == PRODUCT) {
                        when (position) {
                            0 -> startActivity<MakerCourseListActivity>(Config.GUID to user.guid, Config.TYPE to 1)
                        }
                    } else if (type == PERSONAL_FILE) {
                        when (position) {
                            0 -> startActivity<MakerIndustryActivity>()
                            1 -> startActivity<MakerPersonalActivity>(Config.GUID to user.guid)
                            2 -> startActivity<AdvantagedInfoActivity>(Config.GUID to user.guid)
                            3 -> startActivity<MakerPhotoMenuActivity>(Config.GUID to user.guid)
                        }
                    } else if (type == COLLECT) {
                        when (position) {
                            0 -> startActivity<CollectCompanyActivity>()
                            1 -> startActivity<CollectProductActivity>()
                            2 -> startActivity<CollectMakerActivity>()
                            3 -> startActivity<CollectCourseActivity>()
                        }
                    }
                }
            }
        }
    }

    class LeftItemBean(
            val id: Int = 0,
            val label: String = "",
            var isChecked: Boolean = false
    ) : Serializable

}